import { View, Image, Text, Button } from "@tarojs/components";
import {
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
  AtCheckbox,
  AtMessage
} from "taro-ui";
import DigitalAdditionAndSubtraction from "../../../../components/DigitalAdditionAndSubtraction";
import toright from "../../../../image/toright.png";
import select from "../../../../image/复选框-选中.png";
import no_select from "../../../../image/复选框-未选择.png";
import { connect } from "react-redux";
import "./index.scss";
import { useState } from "react";
import { useEffect } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import { ImageUrl } from "../../../../utils/request";
import { identity } from "lodash";
import { isLogin } from "../../../../api/login/index";
type cartListType = {
  id: string;
  picture: string;
  title: string;
  price: number;
  num: number;
  count: number;
  onSelect: boolean;
};

const index = props => {
  const [data, SetData] = useState<cartListType[]>();
  const [isALLSelct, SetIsAllSelect] = useState<boolean>(false);
  const [selectCount, SetSelectCount] = useState<number>(0);
  const [allPrice, SetAllPrice] = useState<number>();
  const [isOpened, SetIsOpened] = useState<boolean>(false);
  const [flag, SetFlag] = useState<string>();
  useDidShow(() => {
    const tempList = [];
    console.log(props.cart);

    props.cart.map(item => {
      tempList.push({ ...item, onSelect: true });
    });

    SetData(tempList);

    // 初始化选中状态
    SetIsAllSelect(true);

    // 初始化总钱数和数量

    let priceCount = 0;

    tempList.forEach(item => {
      if (item.onSelect == true) {
        priceCount += item.count * item.price;
      }
    });
    SetAllPrice(priceCount);
    SetSelectCount(tempList.length);
  });
  useEffect(() => {}, []);

  // 改变数据中的数字
  const ChangeDataNumber = (id: string, num: number) => {
    const temp = data.map(i => {
      if (i.id == id) {
        i.count = num;
      }
      return i;
    });

    SetData(temp);
    changeAllprice();

    props.dispatch({
      type: "cart/reduceNumber",
      payload: {
        id: id,
        num: num
      }
    });

    if (num == 0) {
      SetFlag(id);
      SetIsOpened(true);
    }
  };
  // 改变选择状态
  const changeOnSelect = (id: string, statu: boolean) => {
    const temp = data.map(i => {
      if (i.id == id) {
        i.onSelect = statu;
      }
      return i;
    });

    SetData(temp);

    let flag = true;
    let selectCount = 0;

    data.forEach(item => {
      if (item.onSelect == false) {
        flag = false;
      } else {
        selectCount += 1;
      }
    });
    SetIsAllSelect(flag);
    SetSelectCount(selectCount);
    changeAllprice();
  };

  const changeAllprice = () => {
    let priceCount = 0;

    data.forEach(item => {
      if (item.onSelect == true) {
        priceCount += item.count * item.price;
      }
    });
    SetAllPrice(priceCount);
  };

  return (
    <View className="CartListWrapper">
      <AtMessage />
      {/* 头部 */}
      <View className="CartTitle">
        <Text>沃尔玛（桃北东路店）</Text>
        <Image className="CartTitleImage" src={toright}></Image>
      </View>
      {data &&
        data.map(item => {
          return (
            <View className="CartContent at-row" key={item.id}>
              <AtModal
                isOpened={isOpened}
                title="是否移除购物车"
                cancelText="取消"
                confirmText="确认"
                onClose={() => {}}
                onCancel={() => {}}
                onConfirm={async () => {
                  await props.dispatch({
                    type: "cart/pushData",
                    payload: {
                      id: flag
                    }
                  });

                  SetData(data.filter(item => item.id != flag));

                  SetIsOpened(false);
                }}
              />
              {/* 复选框 */}
              <View className="at-col at-col-2 CartCheck">
                <View
                  style={{ width: "100%", height: "100%", display: "flex" }}
                >
                  {item.onSelect ? (
                    <Image
                      className="CartCheckImage"
                      style={{ width: 30, height: 30 }}
                      src={select}
                      onClick={() => {
                        changeOnSelect(item.id, !item.onSelect);
                      }}
                    ></Image>
                  ) : (
                    <Image
                      className="CartCheckImage"
                      style={{ width: 30, height: 30 }}
                      src={no_select}
                      onClick={() => {
                        changeOnSelect(item.id, !item.onSelect);
                      }}
                    ></Image>
                  )}
                </View>
              </View>
              {/* 图片 */}
              <View className="at-col at-col-4">
                <View
                  style={{ width: "100%", height: "100%", display: "flex" }}
                >
                  <Image
                    className="CartCheckImage"
                    style={{ width: 100, height: 100 }}
                    src={ImageUrl + item.picture}
                  ></Image>
                </View>
              </View>
              {/* 内容 */}
              <View className="at-col at-col-6" style={{ height: "100%" }}>
                <View className="ContentTitle">{item.title}</View>
                <View
                  style={{
                    fontSize: 13,
                    color: "#f84c31",
                    fontWeight: 700,
                    marginTop: 30
                  }}
                >
                  ￥ {item.price}
                </View>
              </View>
              {/* 数量 */}
              <View className="UtilsPosition">
                <DigitalAdditionAndSubtraction
                  num={item.count}
                  id={item.id}
                  ChangeDataNumber={ChangeDataNumber}
                />
              </View>
            </View>
          );
        })}

      {/* 结算 */}

      <View className="CartTail at-row">
        <View className="at-col at-col-2">
          <View
            style={{
              width: "100%",
              height: "100%",
              display: "flex"
            }}
          >
            {isALLSelct ? (
              <Image
                className="CartCheckImage"
                style={{ width: 30, height: 30 }}
                src={select}
                onClick={() => {
                  const temp = data.map(item => {
                    item.onSelect = false;
                    return item;
                  });
                  SetIsAllSelect(false);
                  SetData(temp);
                  SetSelectCount(0);
                  changeAllprice();
                }}
              ></Image>
            ) : (
              <Image
                className="CartCheckImage"
                style={{ width: 30, height: 30 }}
                src={no_select}
                onClick={() => {
                  const temp = data.map(item => {
                    item.onSelect = true;
                    return item;
                  });
                  SetIsAllSelect(true);
                  SetData(temp);
                  SetSelectCount(temp.length);
                  changeAllprice();
                }}
              ></Image>
            )}
          </View>
        </View>
        <View className="TailAccount at-col at-col-6">
          <View style={{ display: "flex", flexDirection: "row-reverse" }}>
            {/*  */}
            <View>
              <Text style={{ color: "#6f6f6f", fontSize: "12px" }}>
                已选:{selectCount}件,
              </Text>
              <Text style={{ fontSize: "12px", fontWeight: "600" }}>
                合计:
                <Text style={{ color: "#f84c31", fontSize: "17px" }}>
                  ￥{Number(allPrice).toFixed(2)}
                </Text>
              </Text>
            </View>
          </View>
        </View>
        <View className="at-col at-col-4">
          <View
            className="TailButton"
            onClick={() => {
              isLogin()
                .then(resp => {
                  if (resp.isLogin) {
                    console.log(selectCount == 0);
                    console.log(selectCount === 0);

                    if (selectCount !== 0) {
                      const tempList = [];
                      const orderList = [];
                      data.forEach(item => {
                        if (item.onSelect) {
                          orderList.push(item);
                        } else {
                          tempList.push(item);
                          props.dispatch({
                            type: "cart/pushData",
                            payload: {
                              id: item.id
                            }
                          });
                        }
                      });
                      SetData(tempList);
                      Taro.navigateTo({ url: "/pages/create_order/index" });
                    } else {
                      Taro.atMessage({
                        message: "请选择商品后再创建订单",
                        type: "error"
                      });
                    }
                  } else {
                    Taro.navigateTo({
                      url: "/pages/Login/index"
                    });
                  }
                })
                .catch(error => {
                  console.log(error);
                });
            }}
          >
            结算
          </View>
        </View>
      </View>
    </View>
  );
};
export default connect(({ cart }) => ({ cart }))(index);
